{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pascal VOC 2012 Restricted (RV-VOC12) Mean IU: 0.627024\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import skimage.io as io\n",
    "import os, sys\n",
    "from PIL import Image\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Use second GPU -- change if you want to use a first one\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = '1'\n",
    "\n",
    "# Add a path to a custom fork of TF-Slim\n",
    "# Get it from here:\n",
    "# https://github.com/warmspringwinds/models/tree/fully_conv_vgg\n",
    "sys.path.append(\"/home/dpakhom1/workspace/my_models/slim/\")\n",
    "\n",
    "# Add path to the cloned library\n",
    "sys.path.append(\"/home/dpakhom1/tf_projects/segmentation/tf-image-segmentation/\")\n",
    "\n",
    "slim = tf.contrib.slim\n",
    "\n",
    "from tf_image_segmentation.models.fcn_32s import FCN_32s\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "from tf_image_segmentation.utils.pascal_voc import pascal_segmentation_lut\n",
    "from tf_image_segmentation.utils.tf_records import read_tfrecord_and_decode_into_image_annotation_pair_tensors\n",
    "from tf_image_segmentation.utils.inference import adapt_network_for_any_size_input\n",
    "from tf_image_segmentation.utils.visualization import visualize_segmentation_adaptive\n",
    "\n",
    "pascal_voc_lut = pascal_segmentation_lut()\n",
    "\n",
    "tfrecord_filename = 'pascal_augmented_val.tfrecords'\n",
    "\n",
    "number_of_classes = 21\n",
    "\n",
    "filename_queue = tf.train.string_input_producer(\n",
    "    [tfrecord_filename], num_epochs=1)\n",
    "\n",
    "image, annotation = read_tfrecord_and_decode_into_image_annotation_pair_tensors(filename_queue)\n",
    "\n",
    "# Fake batch for image and annotation by adding\n",
    "# leading empty axis.\n",
    "image_batch_tensor = tf.expand_dims(image, axis=0)\n",
    "annotation_batch_tensor = tf.expand_dims(annotation, axis=0)\n",
    "\n",
    "# Be careful: after adaptation, network returns final labels\n",
    "# and not logits\n",
    "FCN_32s = adapt_network_for_any_size_input(FCN_32s, 32)\n",
    "\n",
    "\n",
    "pred, fcn_32s_variables_mapping = FCN_32s(image_batch_tensor=image_batch_tensor,\n",
    "                                          number_of_classes=number_of_classes,\n",
    "                                          is_training=False)\n",
    "\n",
    "# Take away the masked out values from evaluation\n",
    "weights = tf.to_float( tf.not_equal(annotation_batch_tensor, 255) )\n",
    "\n",
    "# Define the accuracy metric: Mean Intersection Over Union\n",
    "miou, update_op = slim.metrics.streaming_mean_iou(predictions=pred,\n",
    "                                                   labels=annotation_batch_tensor,\n",
    "                                                   num_classes=number_of_classes,\n",
    "                                                   weights=weights)\n",
    "\n",
    "# The op for initializing the variables.\n",
    "initializer = tf.local_variables_initializer()\n",
    "\n",
    "saver = tf.train.Saver()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    \n",
    "    sess.run(initializer)\n",
    "\n",
    "    saver.restore(sess, \"/home/dpakhom1/tf_projects/segmentation/model_fcn32s_final.ckpt\")\n",
    "    \n",
    "    coord = tf.train.Coordinator()\n",
    "    threads = tf.train.start_queue_runners(coord=coord)\n",
    "    \n",
    "    # There are 904 images in restricted validation dataset\n",
    "    for i in xrange(904):\n",
    "        \n",
    "        image_np, annotation_np, pred_np, tmp = sess.run([image, annotation, pred, update_op])\n",
    "        \n",
    "        # Display the image and the segmentation result\n",
    "        # upsampled_predictions = pred_np.squeeze()\n",
    "        #plt.imshow(image_np)\n",
    "        #plt.show()\n",
    "        #visualize_segmentation_adaptive(upsampled_predictions, pascal_voc_lut)\n",
    "        \n",
    "    coord.request_stop()\n",
    "    coord.join(threads)\n",
    "    \n",
    "    res = sess.run(miou)\n",
    "    \n",
    "    print(\"Pascal VOC 2012 Restricted (RV-VOC12) Mean IU: \" + str(res))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
